'''
Created on Sept 16, 2013

@author: Patrick Janssen
'''

import sys, os
from string import Template
from core.modules.vistrails_module import Module, ModuleError
import json
from constants import *

''' ---------------------------------------------------------------------------
VtkMapper
--------------------------------------------------------------------------- '''
class VtkMapper(Module):
    def compute(self):

        # Check inputs
        if not self.hasInputFromPort("json_input_file"):
            raise ModuleError(self, "Needs json_input")
        json_input_file = self.getInputFromPort("json_input_file")

        #Get the paths of the files
        json_input_file_path = os.path.abspath(json_input_file.name)

        # Get the json data
        with open(json_input_file_path) as data_file:    
            data = json.load(data_file)

        # Create the output file
        json_output_file = self.interpreter.filePool.create_file(suffix=".json")
        json_output_file_path = os.path.abspath(json_output_file.name)
        f = open(json_output_file_path, 'w')
        def w(file, line):
            file.write(line + "\n")

        # Header
        w(f, "# vtk DataFile Version 1.0")
        w(f, "Some lines...")
        w(f, "ASCII")
        w(f, "")
        w(f, "DATASET POLYDATA")

        # Points
        w(f, "POINTS "+str(len(data["points"]))+" float")
        for point in data["points"]:
            w(f, " ".join([str('{0:.20f}'.format(i)) for i in point]))
        w(f, "")

        # Closed Polygons
        closed_polys = [poly for poly in data["polys"] if poly["closed"]]
        total_polygons = len(closed_polys)
        total_polygon_data = total_polygons + len(sum([poly["vertices"] for poly in closed_polys], []))
        w(f, "POLYGONS " + str(total_polygons) + " " + str(total_polygon_data))
        for poly in closed_polys:
            w(f, str(len(poly["vertices"])) + " " + " ".join([str(i) for i in poly["vertices"]]))
        w(f, "")

        # Open Polylines
        open_polys = [poly for poly in data["polys"] if not poly["closed"]]
        total_polylines = len(open_polys)
        total_polyline_data = total_polylines + len(sum([poly["vertices"] for poly in open_polys], []))
        w(f, "LINES " + str(total_polylines) + " " + str(total_polyline_data))
        for poly in open_polys:
            w(f, str(len(poly["vertices"])) + " " + " ".join([str(i) for i in poly["vertices"]]))
        w(f, "")

        # Scalars
        if "scalars" in data:
	        w(f, "POINT_DATA " + str(len(data["points"])))
	        w(f, "SCALARS sample_scalars float 1")
	        w(f, "LOOKUP_TABLE default")
	        for scalar in data["scalars"]:
	        	w(f, str(scalar))
	        w(f, "")

        # Close the file
        f.close()

        # Set output
        self.setResult("json_output_file", json_output_file)


    _input_ports = [
    	("json_input_file",FILE,{"optional":False,"sort_key":1})
    ]

    _output_ports = [
    	("json_output_file",FILE,{"optional":False,"sort_key":1})
    ]